// Package web
// Created by GoLand
// @User: lenora
// @Date: 2023/12/13
// @Time: 17:02

package web

import (
	"camp/microbook/internal/service"
	"github.com/gin-gonic/gin"
	"log"
	"regexp"
)

const phoneRegexPattern = `^1(3[0-9]|4[01456879]|5[0-35-9]|6[2567]|7[0-8]|8[0-9]|9[0-35-9])\d{8}$`

var codeGroup = map[uint8]string{
	1: "login",
}

type CommonHandler struct {
	phoneRegexExp *regexp.Regexp
	codeSvc       service.CodeService
}

func NewCommonHandler(svc service.CodeService) *CommonHandler {
	return &CommonHandler{
		phoneRegexExp: regexp.MustCompile(phoneRegexPattern),
		codeSvc:       svc,
	}
}

func (h *CommonHandler) RegisterRoutes(engine *gin.Engine) {
	engine.POST("/sms/send", h.SendCode)
}

func (h *CommonHandler) SendCode(ctx *gin.Context) {
	type codeReq struct {
		Phone string `json:"phone" binding:"required"`
		Types uint8  `json:"types" binding:"required"`
	}

	var req codeReq
	if err := ctx.Bind(&req); err != nil {
		webResp.InvalidParametersError(ctx)
		return
	}

	if isMatch := h.phoneRegexExp.Match([]byte(req.Phone)); !isMatch {
		webResp.InvalidParametersError(ctx)
		return
	}

	// biz:验证码业务类型
	biz, ok := codeGroup[req.Types]
	if !ok {
		webResp.InternalServiceError(ctx, "code type is wrong")
		return
	}
	err := h.codeSvc.Send(ctx.Request.Context(), biz, req.Phone)
	switch err {
	case nil:
		webResp.ResponseSuccess(ctx, nil)
	//case :
	//TODO:错误处理
	default:
		log.Println(err)
		webResp.InternalServiceError(ctx)
	}
	return
}
